package distributed.controller;

import java.util.UUID;

import org.w3c.dom.NamedNodeMap;

import server.ClientState;
import xml.Message;

/**
 * Controller to handle the signing in of a administrator
 * @author Marcus Menghini
 *
 */
public class AdminLoginController implements IProtocolController{

	/** Processes a message from a client */
	public Message process(ClientState state, Message request) {
		String xmlString;
		//Grab the login credentials
		NamedNodeMap login = request.contents.getFirstChild().getFirstChild().getAttributes();
		
		try { //Authenticate us with the DB
			if (DataBaseController.getInstance().
					authenticateAdmin(login.getNamedItem("name").getNodeValue(),
					login.getNamedItem("password").getNodeValue())) {
				//Generate a random session key
				String key = UUID.randomUUID().toString().substring(19).replace("-", "");
				state.setData(key); //Set the admin's thread to remember the key
				xmlString = Message.responseHeader(request.id()) + "<adminResponse key='" +
						 key + "'/></response>";
			}
			else {
				xmlString = Message.responseHeader(request.id(), "Invalid Login") +
				"<adminResponse key=''/></response>";
			}
		} catch (Exception e) {
			xmlString = Message.responseHeader(request.id(), "Invalid Login") +
			"<adminResponse key=''/></response>";
		}
		
		return new Message(xmlString); //Send back our response
	}

	/**
	 * @return AdminLoginController
	 */
	public IProtocolController newCopy() {
		return new AdminLoginController();
	}

}
